import { refreshTokenAxios } from '@/api/account';
import type { AppStore } from '@/pinia/app';
import { mpLogin } from '@/utils/mp';
import { mpLoginRegisterAxios } from '@/api/account';

/** 自动登录的队列 */
let refreshList: ((res: { code: number; msg: string }) => void)[] = [];
let refreshing = false;
/**
 * 自动登录
 */
export function refreshToken(appStore: AppStore): Promise<string> {
  return new Promise<string>((resolve, reject) => {
    refreshList.push((state) => {
      try {
        state.code === 200 ? resolve(state.msg) : reject(false);
      } catch (error) {}
    });
    if (!refreshing) {
      refreshing = true;
      _refreshToken(appStore)
        .then((res) => {
          refreshList.forEach((cb) => {
            cb(res);
          });
          refreshing = false;
          refreshList = [];
        })
        .catch(() => {
          refreshList.forEach((cb) => {
            cb({ code: 40003, msg: '代码错误，SX2004' });
          });
          refreshing = false;
          refreshList = [];
        });
    }
  });
}

/**
 * 自动登录
 */
async function _refreshToken(appStore: AppStore) {
  try {
    // #ifdef MP-WEIXIN || MP-TOUTIAO || MP-KUAISHOU
    const res_small = await mpLogin();
    appStore.setIsLoginLoging(true);
    const res2 = await mpLoginRegisterAxios({
      code: res_small.code,
      channelId: appStore.launchQuery.channelId || undefined,
      referralLinkId: appStore.launchQuery.referralLinkId || undefined,
      clickid: appStore.launchQuery.clickid || undefined,
      projectId: appStore.launchQuery.projectid || undefined,
      promotionId: appStore.launchQuery.promotionid || undefined,
      wxFinderId: appStore.launchQuery.wxFinderId || undefined,
      launchQuery: JSON.stringify(appStore.launchQuery || {}),
      iaaFlag: appStore.launchQuery.iaaFlag || 0,
      launchQueryPramas: appStore.launchQuery || {},
    });
    appStore.setAccessToken(res2.data.accessToken || '');
    appStore.setRefreshToken(res2.data.refreshToken || '');
    appStore.setPrivateKeyStr(res2.data.privateKeyStr || '');
    return Promise.resolve({ code: 200, msg: res2.data.accessToken });
    // #endif

    const res = await refreshTokenAxios(appStore.refresh_token || '');
    appStore.setAccessToken(res.data.accessToken || '');
    appStore.setRefreshToken(res.data.refreshToken || '');
    appStore.setPrivateKeyStr(res.data.privateKeyStr || '');
    return Promise.resolve({ code: 200, msg: res.data.accessToken });
  } catch (error) {
    return Promise.reject({ code: 40003, msg: '代码错误，SX2003' });
  }
}
